package stud.mpgame.flash.scene;

import flash.display.DisplayObject;
import flash.display.Sprite;

import flash.events.Event;
import flash.events.MouseEvent;

import stud.mpgame.flash.IScene;

import stud.mpgame.flash.gui.ConnectFrame;

import stud.mpgame.flash.net.description.LoginMessageDescription;

import stud.mpgame.flash.net.userobject.LoginUserObject;

import stud.mpgame.network.Message;
import stud.mpgame.network.MessageDescription;
import stud.mpgame.network.NetworkMonitor;

/**
 * 22.03.2011 23:35
 * @author GreK
 */
class ConnectScene extends Sprite, implements IScene {
	
	public static inline var NAME = "ConnectScene";

	public static var POLICY_PORT:Int = 843;
	
	private var protocolVersion:Int;
	private var networkMonitor:NetworkMonitor;
	
	private var connectFrame:ConnectFrame;
	
	private var port:Int;
	private var nickname:String;
	private var userID:Int;
	
	public function new() {
		super();
	    connectFrame = new ConnectFrame(this.handleConnectClick);
		addChild(connectFrame);
	}
	
	public function handleConnectClick(host:String, portString:String, userID:String, nickname:String):Void {
		this.port = Std.parseInt(portString);
		this.nickname = nickname;
		this.userID = Std.parseInt(userID);
		
		if ( host != "" && portString != null ) {            
          networkMonitor.bind(host, port, POLICY_PORT);
          networkMonitor.addSessionOpenedListener(handleSocketConnect);
	    }
	}
	
	
	private function handleSocketConnect(e:Event) {
		var message:Message = new Message(networkMonitor, LoginMessageDescription.getInstance());
		var login:LoginUserObject = new LoginUserObject(nickname, userID);
		message.putUserObject(login);
		message.send();
        
		trace("switch to loading scene");
		Main.getInstance().setScene(LoadingScene.NAME, { networkMonitor: networkMonitor, nickname: nickname, userID: userID } );
	}
	
	public function getName():String {
		return NAME;
	}
	
	public function init(data:Dynamic):Void {
        this.protocolVersion = 1;
        this.networkMonitor = new NetworkMonitor(protocolVersion);
		
		MessageDescription.registerDescription(LoginMessageDescription.getInstance());
	}
	
	public function clear():Void {
		connectFrame.hide();
		MessageDescription.unRegisterDescription(LoginMessageDescription.getInstance());
	}
	
	public function update(deltaTime:Int):Void {
		
	}
	
	public function getContentRoot():DisplayObject {
		return this;
	}
	
}